package edu.uoc.tdp.pac4.client.Academic;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;
import java.util.List;


import edu.uoc.tdp.pac4.beans.Aula;
import edu.uoc.tdp.pac4.beans.Group;
import edu.uoc.tdp.pac4.beans.Usuari;
import edu.uoc.tdp.pac4.client.ClientConnectionHelper;
import edu.uoc.tdp.pac4.common.AcademicManagementInterface;
import edu.uoc.tdp.pac4.common.util.LanguageUtils;

/*
 * Creates a JFrame to assign resources (teacher and room) to a Group
 * @author Laia
 *
 */
public class Group_AssignResources extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	AcademicManagementInterface academicManagement;
	ClientConnectionHelper connectionHelper_;

	private JPanel contentPane;
	private JTextField textField_3;
	private JTextField textField;
	private JTextField textField_1;
	private JTextField textField_2;
	private JTextField textField_4;
	private JComboBox<String> comboBox_3;
	private JComboBox<String> comboBox_2;

	/**
	 * Creates de JFrame to assign resources the Group group
	 * 
	 * @param group
	 * @param connectionHelper
	 */
	public Group_AssignResources(final Group group,
			ClientConnectionHelper connectionHelper) {
		connectionHelper_ = connectionHelper;
		academicManagement = connectionHelper_.getAcademicManager();
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 447);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		JButton btnDesar = new JButton(
				LanguageUtils.getMessage("client.management.button.save"));
		btnDesar.setBounds(10, 375, 89, 23);
		contentPane.add(btnDesar);
		btnDesar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					desar(group);
				} catch (RemoteException e) {
					e.printStackTrace();
				}
			}
		});

		JButton btnCancellar = new JButton(
				LanguageUtils.getMessage("client.management.button.cancel"));
		btnCancellar.setBounds(335, 375, 89, 23);
		contentPane.add(btnCancellar);
		btnCancellar.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dispose();
			}
		});

		JPanel panel = new JPanel();
		panel.setBounds(10, 36, 414, 193);
		contentPane.add(panel);
		panel.setLayout(null);

		JLabel lblId = new JLabel(
				LanguageUtils.getMessage("client.management.button.id"));
		lblId.setBounds(10, 10, 46, 14);
		panel.add(lblId);

		JLabel lblNomDelCurs = new JLabel(
				LanguageUtils.getMessage("client.management.button.nameCourse"));
		lblNomDelCurs.setBounds(10, 45, 129, 14);
		panel.add(lblNomDelCurs);

		JLabel lblTorn = new JLabel(
				LanguageUtils.getMessage("client.management.button.shift"));
		lblTorn.setBounds(10, 80, 46, 14);
		panel.add(lblTorn);

		textField_3 = new JTextField();
		textField_3.setForeground(Color.DARK_GRAY);
		textField_3.setEditable(false);
		textField_3.setColumns(10);
		textField_3.setBounds(149, 7, 37, 20);
		textField_3.setText(group.getGroupId() + "");
		panel.add(textField_3);

		JLabel label = new JLabel(
				LanguageUtils.getMessage("client.management.button.teacher"));
		label.setBounds(10, 115, 74, 14);
		panel.add(label);

		JLabel label_3 = new JLabel(
				LanguageUtils.getMessage("client.management.button.room"));
		label_3.setBounds(10, 150, 46, 14);
		panel.add(label_3);

		textField = new JTextField();
		textField.setForeground(Color.DARK_GRAY);
		textField.setEditable(false);
		textField.setColumns(10);
		textField.setBounds(149, 42, 177, 20);
		textField.setText(group.getName());
		panel.add(textField);

		textField_1 = new JTextField();
		textField_1.setForeground(Color.DARK_GRAY);
		textField_1.setEditable(false);
		textField_1.setColumns(10);
		textField_1.setBounds(149, 77, 177, 20);
		textField_1.setText(group.getShift().toString());
		panel.add(textField_1);

		textField_2 = new JTextField();
		textField_2.setForeground(Color.DARK_GRAY);
		textField_2.setEditable(false);
		textField_2.setColumns(10);
		textField_2.setBounds(149, 112, 177, 20);
		if (group.getTeacher() != null) {
			textField_2.setText(group.getTeacher().getNombre() + " "
					+ group.getTeacher().getApellidos());
		}

		panel.add(textField_2);

		textField_4 = new JTextField();
		textField_4.setForeground(Color.DARK_GRAY);
		textField_4.setEditable(false);
		textField_4.setColumns(10);
		textField_4.setBounds(149, 147, 177, 20);

		if (group.getAula().getNom() != null) {
			textField_4.setText(group.getAula().getNom() + "");
		}

		panel.add(textField_4);

		JLabel lblGestiDeGrups = new JLabel(
				LanguageUtils
						.getMessage("client.management.button.addResources"));
		lblGestiDeGrups.setBounds(10, 11, 167, 14);
		contentPane.add(lblGestiDeGrups);

		JPanel panel_1 = new JPanel();
		panel_1.setLayout(null);
		panel_1.setBounds(10, 241, 414, 90);
		contentPane.add(panel_1);

		JLabel label_1 = new JLabel(
				LanguageUtils.getMessage("client.management.button.teacher"));
		label_1.setBounds(10, 24, 74, 14);
		panel_1.add(label_1);

		comboBox_2 = new JComboBox<String>();
		comboBox_2.setBounds(150, 21, 224, 20);
		try {
			comboBox_2.setModel(posarProfes());
		} catch (RemoteException e1) {
			e1.printStackTrace();
		}
		panel_1.add(comboBox_2);

		JLabel label_2 = new JLabel(
				LanguageUtils.getMessage("client.management.button.room"));
		label_2.setBounds(10, 59, 46, 14);
		panel_1.add(label_2);

		comboBox_3 = new JComboBox<String>();
		comboBox_3.setBounds(149, 57, 225, 20);
		try {
			comboBox_3.setModel(posarAules());
		} catch (RemoteException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		panel_1.add(comboBox_3);
	}

	/**
	 * Saves the teacher and room of a group
	 * 
	 * @param group
	 * @throws RemoteException
	 */
	private void desar(Group group) throws RemoteException {
		String error = LanguageUtils.getMessage("client.management.error");
		String nameProf;
		String lastname, firstname;

		//gets the name of the teacher
		try {
			nameProf = (String) comboBox_2.getSelectedItem();
			String delims = "[ ]+";
			String[] tokens = nameProf.split(delims);
			firstname = tokens[0];
			lastname = tokens[1];
		} catch (NullPointerException e) {
			warn(LanguageUtils.getMessage("client.management.error.selecprof"),
					error);

			return;

		}
		
		//gets the name of the room
		String nameRoom = null;
		nameRoom = (String) comboBox_3.getSelectedItem();

		if (nameRoom == null) {
			warn(LanguageUtils.getMessage("client.management.error.selecroom"),
					error);
		} else {
			Boolean profOcupat = false;
			Boolean aulaOcupada = false;
			
			//gets the Room from its name and checks whether it is already occupied

			Aula aula;
			aula = academicManagement.findRoomByName(nameRoom);

			List<Group> groupsByAula = academicManagement.listGroupsByAula(aula
					.getIdAula());

			for (int i = 0; i < groupsByAula.size(); i++) {

				if (groupsByAula.get(i).getGroupId() != group.getGroupId()
						&& groupsByAula.get(i).getFinalDate()
								.after(group.getStartDate())
						&& groupsByAula.get(i).getShift()
								.equals(group.getShift())) {
					aulaOcupada = true;
				}
			}
			
			//gets the teacher from his/her name and checks whether he is already assigned to another group.

			Usuari prof;
			prof = academicManagement.findTeacherByNames(firstname, lastname);

			List<Group> groupsByProf = academicManagement.listGroupsByProf(prof
					.getNIF());

			for (int i = 0; i < groupsByProf.size(); i++) {

				if (groupsByProf.get(i).getGroupId() != group.getGroupId()
						&& groupsByProf.get(i).getFinalDate()
								.after(group.getStartDate())
						&& groupsByProf.get(i).getShift()
								.equals(group.getShift())) {
					profOcupat = true;
				}
			}
			
			
			// if room and teacher are free, asks the user to confirm the assignment
			if (!aulaOcupada && !profOcupat) {

				int ax = JOptionPane
						.showConfirmDialog(
								null,
								LanguageUtils
										.getMessage("client.management.button.update.resources.question"));
				if (ax == JOptionPane.YES_OPTION) {

					academicManagement.saveResources(group.getGroupId(), aula,
							prof);

					JOptionPane
							.showMessageDialog(
									null,
									LanguageUtils
											.getMessage("client.management.button.resources.updated"),
									null, JOptionPane.INFORMATION_MESSAGE);

					dispose();
				}

			}
			
			//otherwise, the user is warned
			if (profOcupat && !aulaOcupada) {
				warn(LanguageUtils
						.getMessage("client.management.error.busyProf"),
						error);
			}
			if (aulaOcupada && !profOcupat) {
				warn(LanguageUtils
						.getMessage("client.management.error.busyRoom"),
						error);
			}
			if (aulaOcupada && profOcupat) {
				warn(LanguageUtils
						.getMessage("client.management.error.busyRoomAndProf"),
						error);
			}

		}

	}

	/**
	 * Populates a comboBoxModel with teacher's names
	 * 
	 * @return model
	 * @throws RemoteException
	 */
	private DefaultComboBoxModel<String> posarProfes() throws RemoteException {
		List<Usuari> teachers;
		teachers = academicManagement.listTeachers();
		DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>();
		model.addElement(null);
		for (int i = 0; i < teachers.size(); i++) {
			model.addElement(teachers.get(i).getNombre() + " "
					+ teachers.get(i).getApellidos());
		}
		return model;

	}

	/**
	 * Populates a comboBoxModel with room's names
	 * 
	 * @return model
	 * @throws RemoteException
	 */
	private DefaultComboBoxModel<String> posarAules() throws RemoteException {
		List<Aula> aules;
		aules = academicManagement.listRooms();
		DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>();
		model.addElement(null);
		for (int i = 0; i < aules.size(); i++) {
			model.addElement(aules.get(i).getNom());
		}
		return model;

	}

	/**
	 * Produces a warning JOptionPane
	 * 
	 * @param main
	 * @param sec
	 */
	public void warn(String main, String sec) {
		JOptionPane.showMessageDialog(null, main, sec,
				JOptionPane.ERROR_MESSAGE);
	}

}
